import json
import threading
import time
from fastapi import APIRouter, Request, HTTPException
from pydantic import BaseModel
from typing import Optional
from config.database_connect import get_db_connection
from paho.mqtt import client as mqtt_client

appEnvironmentUpdate = APIRouter()

BROKER = "106.14.117.188"
PORT = 1883
TOPIC = "esp32/environment_data"
MQTT_USER = "admin"
MQTT_PASSWORD = "1234"

class EnvironmentData(BaseModel):
    soil_moisture: Optional[float] = None
    soil_temperature: Optional[float] = None    # 新增土壤温度
    air_temperature: Optional[float] = None     # 明确空气温度字段
    air_humidity: Optional[float] = None
    light_intensity: Optional[float] = None

    class Config:
        schema_extra = {
            "example": {
                "soil_moisture": 45.5,
                "soil_temperature": 18.0,
                "air_temperature": 25.0,
                "air_humidity": 60.0,
                "light_intensity": 800.0
            }
        }

def save_environment_data(user_id, data, device_id='default'):
    print(f"[SAVE] 开始保存环境数据，用户ID: {user_id}")
    print(f"[DATA] 数据内容: {data}, device_id: {device_id}")

    db = get_db_connection()
    if not db:
        print("[ERROR] 数据库连接失败")
        return False

    try:
        with db.cursor() as cursor:
            sql = """
            INSERT INTO plant_data
            (user_id, device_id, soil_moisture, soil_temperature, air_temperature, air_humidity, light_intensity)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
            """
            params = (
                user_id,
                device_id,
                data.get('soil_moisture'),
                data.get('soil_temperature'),
                data.get('air_temperature'),
                data.get('air_humidity'),
                data.get('light_intensity')
            )
            print(f"[SQL] 执行SQL插入，参数: {params}")
            cursor.execute(sql, params)
            db.commit()
        print("[SUCCESS] 环境数据保存成功")
        return True

    except Exception as e:
        db.rollback()
        import traceback
        traceback.print_exc()
        print(f"[ERROR] 环境数据保存失败: {str(e)}")
        return False
    finally:
        db.close()
        print("[DB] 数据库连接已关闭")

# MQTT 回调、客户端初始化部分保持你的逻辑，只是解析字段做调整：

def on_message(client, userdata, msg):
    print(f"[MQTT] 收到消息，主题: {msg.topic}")
    try:
        payload = msg.payload.decode("utf-8")
        print(f"[MQTT] 原始载荷: {payload}")
        raw = json.loads(payload)
        print("[MQTT] 解析后的数据:", raw)

        # 映射 MQTT 数据字段到你的数据模型字段
        mapped = {
            'soil_moisture': raw.get('soilHumidity'),
            'soil_temperature': raw.get('soilTemperature'),   # 如果有这个字段
            'air_temperature': raw.get('temperature'),
            'air_humidity': raw.get('humidity'),
            'light_intensity': raw.get('lightIntensity')     # 如果有这个字段
        }
        print("[MQTT] 映射后的数据:", mapped)

        default_user_id = 1   # 确保 users 表里确实存在 user_id=1
        default_device_id = raw.get('deviceId', 'default')  # 如果 MQTT 有 deviceId 字段的话

        success = save_environment_data(default_user_id, mapped, default_device_id)
        if success:
            print("[SUCCESS] MQTT数据已自动保存到数据库")
        else:
            print("[ERROR] MQTT数据保存失败")

    except json.JSONDecodeError as e:
        print(f"[ERROR] MQTT JSON解析错误: {e}")
    except Exception as e:
        print(f"[ERROR] MQTT数据处理错误: {e}")

# API 路由部分修改以使用新的字段模型：

@appEnvironmentUpdate.post("/environment")
async def update_environment(data: EnvironmentData, request: Request):
    print("[API] 收到HTTP环境数据上传请求")
    print(f"[DATA] 上传数据: {data.dict()}")

    user_id = request.session.get("user_id")
    username = request.session.get("username")

    if not user_id:
        print("[AUTH] 用户未登录，拒绝访问")
        raise HTTPException(status_code=401, detail="用户未登录")

    success = save_environment_data(user_id, data.dict())
    if success:
        print("[SUCCESS] HTTP环境数据保存成功")
        return {
            "status": "success",
            "user_id": user_id,
            "username": username,
            "message": "环境数据保存成功",
            "data": data.dict()
        }
    else:
        print("[ERROR] HTTP环境数据保存失败")
        raise HTTPException(status_code=500, detail="数据保存失败")

# 其余 /environment/current, /environment/history, /environment/mqtt-status API 不用修改字段名，但可以考虑返回更一致的字段名
